package ar.com.spsolutions.splibrary.general;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.transaction.annotation.Transactional;

import ar.com.spsolutions.splibrary.services.UserService;
import ar.com.spsolutions.splibrary.user.User;

public class RoleConverterService {
	public static enum RolesEnum {
		ROLE_GUEST, ROLE_USER, ROLE_LIBRARIAN;

	}

	public final static String ROLE_USER = "ROLE_USER";
	public final static String ROLE_LIBRARIAN = "ROLE_LIBRARIAN";
	public static final String ROLE_GUEST = "ROLE_GUEST";

	private UserService userService;

	@Transactional(readOnly = true)
	public Roles getRoleFor(final User user) {
		final Roles tmpRoles = new Roles(RolesEnum.ROLE_GUEST.toString());
		if (user == null) {
			return tmpRoles;
		}
		final User tmpUser = this.getUserService().get(user);
		tmpRoles.add(RolesEnum.ROLE_USER.toString());
		if ((tmpUser != null) && tmpUser.isAdmin()) {
			tmpRoles.add(RolesEnum.ROLE_LIBRARIAN.toString());
		}
		return tmpRoles;
	}

	public UserService getUserService() {
		return this.userService;
	}

	public void setUserService(final UserService userService) {
		this.userService = userService;
	}

	public List<GrantedAuthority> getGrants(final User tmpUser) {
		final Roles roles = this.getRoleFor(tmpUser);
		final List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();
		for (final String role : roles) {
			grantedAuthorities.add(new GrantedAuthorityImpl(role));
		}
		return grantedAuthorities;
	}

}
